package logic

import (
	"context"
	"errors"
	"practice-one/models/mysql"

	"practice-one/userrpc/internal/svc"
	"practice-one/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsAddLogic) GoodsAdd(in *userrpc.GoodsAddRequest) (*userrpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line

	var findUser mysql.User
	if err := findUser.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("该用户不存在")
	}
	if in.Title == "" || in.Price == 0 || in.Content == "" || in.GoodsType == "" {
		return nil, errors.New("标题、分类、价格、描述为必填项")
	}

	goods := &mysql.Goods{
		UserId:    in.UserId,
		Title:     in.Title,
		GoodsType: in.GoodsType,
		Price:     in.Price,
		Content:   in.Content,
	}
	if err := goods.GoosAdd(mysql.DB); err != nil {
		return nil, err
	}
	return &userrpc.GoodsAddResponse{
		GoodsId: int64(goods.ID),
	}, nil
}
